package com.example.zsr.downloadcontinue;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.zsr.downloadcontinue.ToolUtils.FileInfo;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by zhengshaorui on 2017/2/22.
 */

public class DowaloadService extends Service {
    private static final String TAG = "zsr";
    private static Context mContext;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        FileInfo mFileInfo = (FileInfo) intent.getSerializableExtra("fileinfo");
        int status = intent.getIntExtra("service",0);
        if (status == 1){
            Log.d(TAG, "start: "+mFileInfo);
            DownloadTask.isPause  = false;
            new download(mFileInfo).start();
        }else{
            Log.d(TAG, "stop: ");
            DownloadTask.isPause =  true;

        }


        return super.onStartCommand(intent, flags, startId);
    }


    class download extends  Thread{
        FileInfo mFileInfo;
        public download(FileInfo fileinfo){
            this.mFileInfo = fileinfo;
        }
        @Override
        public void run() {
            super.run();
            HttpURLConnection conn = null;
            try {
                URL url = new URL(mFileInfo.getApkurl());
                conn = (HttpURLConnection) url.openConnection();
                //加上这句是为了防止connection.getContentLength()获取不到
                conn.setRequestProperty("Accept-Encoding", "identity");
                conn.setRequestMethod("GET");
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);
                if (conn.getResponseCode() == 200){
                    int length = conn.getContentLength();
                    if (length < 0) return;
                    else mFileInfo.setLength(length);
                }

                File dir = new File(mFileInfo.getFileDir());
                if (!dir.exists()){
                    mFileInfo.setDir(dir);
                }
                mFileInfo.setDir(dir);
                Log.d(TAG, "run: "+mFileInfo);


                new DownloadTask(mContext).download(mFileInfo);

            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "error: "+e.toString());
            }finally {
                conn.disconnect();
            }
        }
    }
}
